/**
 * API 路由包装器
 * 提供统一的错误处理、用户认证和 RLS 支持
 */

import { NextResponse } from 'next/server'
import { extractUserIdFromRequest, logSecurityEvent } from './rls-middleware'

/**
 * API 路由包装器
 * 自动处理用户认证、错误处理和安全日志
 */
export function withApiHandler(handler, options = {}) {
    const {
        requireAuth = false,
        logActions = true,
        resource = 'unknown'
    } = options

    return async (request, context) => {
        try {
            // 提取用户ID
            const userId = extractUserIdFromRequest(request)

            // 检查认证要求
            if (requireAuth && !userId) {
                return NextResponse.json({
                    success: false,
                    error: {
                        code: 'UNAUTHORIZED',
                        message: '需要登录才能访问此资源'
                    }
                }, { status: 401 })
            }

            // 将用户ID添加到请求对象
            request.userId = userId

            // 记录API访问日志
            if (logActions && userId) {
                const method = request.method.toLowerCase()
                await logSecurityEvent(userId, `api_${method}`, resource, context?.params?.id || 'unknown', true)
            }

            // 调用原始处理器
            const response = await handler(request, context)

            return response

        } catch (error) {
            console.error(`API错误 [${request.method} ${request.url}]:`, error)

            // 记录错误日志
            if (logActions && request.userId) {
                const method = request.method.toLowerCase()
                await logSecurityEvent(request.userId, `api_${method}_error`, resource, context?.params?.id || 'unknown', false)
            }

            // 处理特定错误类型
            if (error.message.includes('权限不足')) {
                return NextResponse.json({
                    success: false,
                    error: {
                        code: 'FORBIDDEN',
                        message: '权限不足'
                    }
                }, { status: 403 })
            }

            if (error.message.includes('not found') || error.message.includes('不存在')) {
                return NextResponse.json({
                    success: false,
                    error: {
                        code: 'NOT_FOUND',
                        message: '资源不存在'
                    }
                }, { status: 404 })
            }

            // 通用错误响应
            return NextResponse.json({
                success: false,
                error: {
                    code: 'INTERNAL_ERROR',
                    message: '服务器内部错误',
                    details: process.env.NODE_ENV === 'development' ? error.message : undefined
                }
            }, { status: 500 })
        }
    }
}

/**
 * 需要认证的 API 路由包装器
 */
export function withAuth(handler, options = {}) {
    return withApiHandler(handler, { ...options, requireAuth: true })
}

/**
 * 产品相关 API 路由包装器
 */
export function withProductApi(handler, options = {}) {
    return withApiHandler(handler, { ...options, resource: 'products' })
}

/**
 * 用户相关 API 路由包装器
 */
export function withUserApi(handler, options = {}) {
    return withApiHandler(handler, { ...options, resource: 'users' })
}

/**
 * 标准化成功响应
 */
export function successResponse(data, message = null, status = 200) {
    return NextResponse.json({
        success: true,
        data,
        message
    }, { status })
}

/**
 * 标准化错误响应
 */
export function errorResponse(code, message, status = 400, details = null) {
    return NextResponse.json({
        success: false,
        error: {
            code,
            message,
            details
        }
    }, { status })
}

/**
 * 验证请求参数
 */
export function validateParams(params, required = []) {
    const missing = required.filter(field => !params[field])

    if (missing.length > 0) {
        throw new Error(`缺少必需参数: ${missing.join(', ')}`)
    }

    return true
}

/**
 * 分页响应包装器
 */
export function paginatedResponse(items, pagination, filters = null) {
    return successResponse({
        items,
        pagination,
        filters
    })
}

export default {
    withApiHandler,
    withAuth,
    withProductApi,
    withUserApi,
    successResponse,
    errorResponse,
    validateParams,
    paginatedResponse
}